#include "userFlash.h"
#include "main.h"

#define FLASH_WAIT_NOBUSY() while((FLASH->SR & FLASH_SR_BSY)!=0){}


	

void flashUnlock(void)
{
	FLASH->KEYR=FLASH_KEY1;
	FLASH->KEYR=FLASH_KEY2;
}

void flashLock(void)
{
	FLASH->CR|=FLASH_CR_LOCK;
}
void flashInit()
{
	flashUnlock();
	FLASH->SR|=0X34;   //CLEAR FLAG: EOP  WRPRTERR  PGERR
	flashAppErase();  //擦除用户区域数据
}
//擦除一页的flash
void flashErasePage(uint32_t pAdd)
{
	FLASH_WAIT_NOBUSY();					//等待之前操作完成
	FLASH->CR |= FLASH_CR_PER; 		//打开也擦除操作
	FLASH->AR = pAdd;             //设置要擦除的页地址
	FLASH->CR |= FLASH_CR_STRT;   //开始擦除
	FLASH_WAIT_NOBUSY();          //等待擦除完成
	FLASH->CR &= ~FLASH_CR_PER;   //关闭页擦除操作
}
//擦除iap中app区域的flash
void flashAppErase()
{
	uint32_t  tadd=APP_ADD;
	while(tadd<=LAST_PAGE_ADD)
	{
		flashErasePage(tadd);
		tadd+=FLASH_PAGE_SIZE;
	}
}
//向指定地址写入两个byte（flash写操作一次只能写入两个byte）
void flashWriteHalfWord(uint32_t address,uint16_t data)
{
	FLASH_WAIT_NOBUSY();      //等待之前操作完成
	FLASH->CR|=FLASH_CR_PG;   //打开flash编程模式
	*(__IO uint16_t *)address=(uint16_t)data;  //向地址写数据
	FLASH_WAIT_NOBUSY();       //等待操作完成
	FLASH->CR &= ~FLASH_CR_PG; //关闭flash编程模式
}
void flashAppWrite(__IO uint32_t address,uint16_t* data,uint16_t len)
{
	uint16_t i;
	for(i=0;(i<len)&&(address<=(FLASH_END_ADD-2));i++)
	{
		flashWriteHalfWord(address,*(uint16_t *)(data+i));
		address+=2;
	}
}
void flashObaunch(void)
{
  /* Set the OBL_Launch bit to launch the option byte loading */
  FLASH->CR |= FLASH_CR_OBL_LAUNCH;
}

//uint8_t getObUserData(uint8_t num)
//{
//	if(num==0)
//	{
//		return (uint8_t)(FLASH->OBR >> 16);
//	}
//	else if(num==1)
//	{
//		return (uint8_t)(FLASH->OBR >> 24);
//	}
//	else return 0xff;
//}



